Skip to content

feat: improve provider management and prompt templates UI - #16

Merged
luorome31 merged 14 commits into
mainfrom
feat/T011-T012-popup-options-ui
Mar 29, 2026
Merged

luorome31 merged 14 commits into
mainfrom
feat/T011-T012-popup-options-ui

Conversation

@luorome31

Copy link
Copy Markdown
Owner

Summary

Provider Management Improvements

  • Remove provider count limit - users can now add unlimited custom providers
  • Fix Popup display name to use user-defined name field instead of provider type
  • Add Save button to provider cards for explicit saving
  • Use id instead of provider name for provider selection

Prompt Templates UI

  • Add Save button for prompt template changes
  • Improve template name input styling with proper border and focus states
  • Increase textarea min-height and add auto-resize behavior
  • Clarify {{text}} variable usage with better helper text

Technical Changes

  • Update llmService to find provider by id with fallback to old format
  • Track unsaved changes separately for providers and prompts
  • Fix missing afterEach import in tests

Test plan

  • All 115 tests passing
  • TypeScript type check passing
  • ESLint passing
  • Build successful

Related Issues

  • Closes T019 (LLM integration with storage configuration)
  • Closes T020 (Options UI beautification)

- Extend APIKeyItem with name, url, displayOrder fields
- Modify llmService to read selectedProvider/apiKeys/prompts from storage
- Update Options page to support configuring name, url, displayOrder
- Update Popup to sort providers by displayOrder from storage
- Update tests to mock chrome.storage.local instead of static apiConfig
- Options.test.tsx: Test new API key fields (name, url, displayOrder)
- Popup.test.tsx: Test provider sorting by displayOrder
- Total: 17 new tests (100 -> 117)
Critical fixes from code review:
- Add model and endpoint optional fields to APIKeyItem
- llmService now uses provider-specific defaults with APIKeyItem override
- DeepSeek: deepseek-chat, /chat/completions
- OpenAI: gpt-3.5-turbo, /v1/chat/completions
- Local: gpt-3.5-turbo, /v1/chat/completions
- Options UI now shows model and endpoint inputs
Changes:
- PROVIDERS: ['DeepSeek', 'OpenAI', 'Local'] -> ['OpenAI', 'DeepSeek', 'SiliconFlow', 'TogetherAI', 'Ollama', 'Custom']
- llmService: Updated getProviderDefaults() for all new providers
- Options: Updated handleTestApiKey() with new provider defaults
- Tests: Updated to reflect new provider list

Provider defaults:
- OpenAI: gpt-3.5-turbo, /v1/chat/completions
- DeepSeek: deepseek-chat, /chat/completions
- SiliconFlow: deepseek-chat, /v1/chat/completions
- TogetherAI: meta-llama/Llama-3-70b-chat, /v1/chat/completions
- Ollama: llama3, /api/chat (localhost:11434)
- Custom: requires full configuration
…ards

- Provider pre-configuration: Each provider (OpenAI, DeepSeek, SiliconFlow, TogetherAI, Ollama, Custom) is pre-populated with default URL, model, and endpoint
- User only needs to fill in API key
- Card-based layout instead of cramped row layout
- Reset to defaults button per provider
- Test button for API key validation
- Better spacing and responsive design

Provider defaults:
- OpenAI: api.openai.com, gpt-3.5-turbo, /v1/chat/completions
- DeepSeek: api.deepseek.com, deepseek-chat, /chat/completions
- SiliconFlow: api.siliconflow.cn, deepseek-chat, /v1/chat/completions
- TogetherAI: api.together.xyz, meta-llama/Llama-3-70b-chat, /v1/chat/completions
- Ollama: localhost:11434, llama3, /api/chat
- Custom: requires full configuration
- Use Array.isArray() check for robust initialization
- Fix prompts check to use same pattern
- Ensures first-time users see all 6 provider cards
- Add 'Add' button to add new providers from dropdown
- Display order input with hint 'lower number = higher priority'
- Providers sorted by displayOrder in the grid
- Delete button to remove providers
- Available providers filtered from already added ones
- Remove provider count limit, allow unlimited custom providers
- Fix Popup display name to match user-defined name field
- Add Save button for provider cards and prompt templates
- Use id instead of provider name for provider selection
- Improve template name input styling with proper border and focus
- Increase textarea min-height and add auto-resize behavior
- Clarify {{text}} variable usage in prompt templates
- Update llmService to find provider by id with fallback
Copilot AI review requested due to automatic review settings March 29, 2026 03:52

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR updates the extension’s provider/prompt configuration flow by moving provider selection toward stored provider entries (with display names, ordering, and explicit saves), refreshing the Options UI for providers and prompt templates, and wiring llmService to read provider + prompt-template configuration from chrome.storage.local.

Changes:

  • Popup provider selector now prefers configured apiKeys (sorted by displayOrder) and uses provider id values for selection.
  • Options page gets a new provider “card” layout with add/reset/test/save actions and prompt-template save + textarea UX improvements.
  • llmService now loads selected provider/prompt from storage and builds requests using stored URL/key plus prompt templates (with legacy fallback for provider selection).

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 13 comments.

Show a summary per file
File Description
src/pages/popup/Popup.tsx Provider dropdown now derives from stored provider items (sorted) and stores selection by id.
src/pages/popup/Popup.test.tsx Updates Popup tests to cover provider sorting/fallback behavior.
src/pages/options/options.css Introduces new Options UI styling for provider cards and improved prompt template inputs.
src/pages/options/Options.tsx Implements provider card management (add/save/reset/test/order) and prompt template save + auto-resize UX.
src/pages/options/Options.test.tsx Updates Options tests for new card layout, save button behavior, and hint text.
src/pages/background/storage.types.ts Expands APIKeyItem schema and updates supported provider list.
src/pages/background/storage.types.test.ts Updates provider-list assertions to match the new PROVIDERS.
src/pages/background/llmService.ts Switches request configuration to storage-based provider/prompt selection and supports provider-id lookup.
src/pages/background/llmService.test.ts Updates llmService tests to use storage-backed configuration and prompt template substitution.
feature-task-list.json Marks T019/T020 as passed.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/pages/options/Options.tsx Outdated
Comment on lines +254 to +255
const endpoint = defaults.endpoint;
const model = defaults.model;

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

handleTestApiKey always uses the provider default endpoint/model, ignoring any per-provider overrides the user edits in the card (item.endpoint/item.model). This makes "Test" potentially test a different route/model than will be used at runtime. Consider looking up the item by id inside handleTestApiKey (or pass model/endpoint as args) and using the configured values with defaults as fallback.

Suggested change
const endpoint = defaults.endpoint;
const model = defaults.model;
const item = apiKeys.find((k) => k.id === id);
const endpoint = item?.endpoint || defaults.endpoint;
const model = item?.model || defaults.model;

Copilot uses AI. Check for mistakes.
Comment on lines 139 to +148
useEffect(() => {
chrome.storage.local.get(STORAGE_KEYS, (result: Partial<StorageSchema>) => {
if (result.apiKeys?.length) setApiKeys(result.apiKeys);
if (result.prompts?.length) setPrompts(result.prompts);
if (Array.isArray(result.apiKeys) && result.apiKeys.length > 0) {
setApiKeys(result.apiKeys);
}
// 不再自动初始化默认provider,让用户自己添加

if (Array.isArray(result.prompts) && result.prompts.length > 0) {
setPrompts(result.prompts);
}

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This loads apiKeys directly from storage into state, but the storage schema for APIKeyItem has changed (new required fields like name/url/displayOrder). Existing installations may have older entries missing these fields, which will cause controlled inputs below to receive undefined values and sorting by displayOrder to behave unpredictably. Consider mapping storage data to a normalized shape here (fill defaults / migrate) before calling setApiKeys.

Copilot uses AI. Check for mistakes.
Comment on lines +404 to +443
<label className="field-label">Display Name</label>
<input
type="text"
className="field-input"
value={item.name}
onChange={(e) => handleUpdateApiKey(item.id, 'name', e.target.value)}
placeholder="Display name..."
/>
</div>

<div className="field-group">
<label className="field-label">API URL</label>
<input
type="text"
className="field-input"
value={item.url}
onChange={(e) => handleUpdateApiKey(item.id, 'url', e.target.value)}
placeholder="https://api.example.com"
/>
</div>

<div className="field-row">
<div className="field-group flex-1">
<label className="field-label">Model</label>
<input
type="text"
className="field-input"
value={item.model}
onChange={(e) => handleUpdateApiKey(item.id, 'model', e.target.value)}
placeholder="gpt-3.5-turbo"
/>
</div>
<div className="field-group flex-1">
<label className="field-label">Endpoint</label>
<input
type="text"
className="field-input"
value={item.endpoint}
onChange={(e) => handleUpdateApiKey(item.id, 'endpoint', e.target.value)}
placeholder="/v1/chat/completions"

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These inputs are controlled via value={item.name/url/model/endpoint}; if any of those fields are undefined (e.g., older stored apiKeys or partially edited items), React will treat the input as uncontrolled and can warn/break editing. Consider using nullish coalescing defaults (e.g. value={item.name ?? ''} and value={item.displayOrder ?? 0}) and ensuring state normalization so values are always strings/numbers.

Copilot uses AI. Check for mistakes.
Comment on lines 532 to 544
<textarea
className="template-textarea"
value={prompt.content}
onChange={(e) => handleUpdatePrompt(prompt.id, 'content', e.target.value)}
placeholder="Enter prompt template..."
onChange={(e) => {
handleUpdatePrompt(prompt.id, 'content', e.target.value);
// Auto-resize
e.target.style.height = 'auto';
e.target.style.height = e.target.scrollHeight + 'px';
}}
placeholder="Enter prompt template... (use &#123;&#123;text&#125;&#125; for selected content)"
aria-label="Template content"
rows={3}
/>

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Auto-resize is only applied on onChange, but the textarea CSS sets overflow: hidden. For prompts that already have multi-line content on initial render, users may not be able to scroll to see all content until they edit. Consider applying the same resize logic on mount/update (e.g., via a ref + useLayoutEffect) or avoiding overflow: hidden so the textarea remains usable before any edits.

Copilot uses AI. Check for mistakes.
Comment on lines +6 to +9
name: string;
url: string;
key: string;
displayOrder: number;

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APIKeyItem now requires name, url, and displayOrder, which is a breaking change for already-stored data (older installs likely have items with only id/provider/key). To keep runtime compatibility, consider making these fields optional in the type (or introducing a StoredAPIKeyItem union) and adding explicit normalization/migration when reading from storage.

Suggested change
name: string;
url: string;
key: string;
displayOrder: number;
name?: string;
url?: string;
key: string;
displayOrder?: number;

Copilot uses AI. Check for mistakes.
Comment thread src/pages/options/Options.tsx Outdated
/>
<div className="var-hint">
Variables: <code>{'{{text}}'}</code> - your selected content
<span className="var-hint-icon">ℹ️</span>

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The info icon is a literal "ℹ️" character; screen readers may announce it redundantly/unhelpfully. Consider marking it aria-hidden="true" and ensuring the explanatory text remains accessible, or replace with an SVG/icon component with appropriate aria-label/title.

Suggested change
<span className="var-hint-icon">ℹ️</span>
<span className="var-hint-icon" aria-hidden="true">ℹ️</span>

Copilot uses AI. Check for mistakes.
Comment on lines 69 to +95
request(params: LLMRequestParams): void {
// 如果已有请求,先中止
this.abort();

const { text, url, prompt, onChunk, onEnd, onError } = params;
const { text, prompt, onChunk, onEnd, onError } = params;
this.currentRequest = new AbortController();

if (apiConfig.debug) {
console.log('[LLMService] Request started:', {
textLength: text.length,
url,
model: apiConfig.model,
baseURL: apiConfig.baseURL,
});
}
// 从 storage 读取配置
chrome.storage.local.get(
['selectedProvider', 'selectedPromptId', 'apiKeys', 'prompts'],
(storageResult: Partial<StorageSchema>) => {
const selectedProvider = storageResult.selectedProvider || 'DeepSeek';
const selectedPromptId = storageResult.selectedPromptId || 'default-summary';
const apiKeys = storageResult.apiKeys || [];
const prompts = storageResult.prompts || [];

// 根据 selectedProvider 查找对应的 APIKeyItem
// selectedProvider 可能是 id(新格式)或 provider 名称(旧格式,兼容)
let apiKeyItem = apiKeys.find((k: APIKeyItem) => k.id === selectedProvider);
if (!apiKeyItem) {
// 兼容旧格式:selectedProvider 可能是 provider 名称
apiKeyItem = apiKeys.find((k: APIKeyItem) => k.provider === selectedProvider);
}
// 如果还是找不到,使用第一个配置好的 provider
if (!apiKeyItem && apiKeys.length > 0) {
apiKeyItem = apiKeys[0];
}

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

request() now reads provider config via an async chrome.storage.local.get callback, but executeRequest() uses this.currentRequest at call time. If a second request starts (and replaces currentRequest) before the first storage callback fires, the first callback can send a fetch using the newer AbortController and still stream chunks to the old callbacks. Capture the AbortController created for this request in a local variable and (a) bail out in the storage callback if it’s no longer current, and/or (b) pass the controller/signal through to executeRequest so each request stays isolated.

Copilot uses AI. Check for mistakes.
Comment thread src/pages/background/llmService.ts Outdated
const userContent = prompt
? `原文:${text}\n\n${prompt}`
: promptTemplate
? promptTemplate.content.replace('{{text}}', text)

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

promptTemplate.content.replace('{{text}}', text) only replaces the first occurrence of {{text}}. If a template uses the variable multiple times, later instances will remain unreplaced. Use replaceAll('{{text}}', text) (or a global regex) to substitute all occurrences.

Suggested change
? promptTemplate.content.replace('{{text}}', text)
? promptTemplate.content.replaceAll('{{text}}', text)

Copilot uses AI. Check for mistakes.
Comment thread src/pages/options/Options.tsx Outdated
Comment on lines +60 to +105
// Provider 默认配置
interface ProviderConfig {
name: string;
url: string;
model: string;
endpoint: string;
}

const PROVIDER_DEFAULTS: Record<string, ProviderConfig> = {
OpenAI: {
name: 'OpenAI',
url: 'https://api.openai.com',
model: 'gpt-3.5-turbo',
endpoint: '/v1/chat/completions',
},
DeepSeek: {
name: 'DeepSeek',
url: 'https://api.deepseek.com',
model: 'deepseek-chat',
endpoint: '/chat/completions',
},
SiliconFlow: {
name: 'SiliconFlow',
url: 'https://api.siliconflow.cn',
model: 'deepseek-chat',
endpoint: '/v1/chat/completions',
},
TogetherAI: {
name: 'TogetherAI',
url: 'https://api.together.xyz',
model: 'meta-llama/Llama-3-70b-chat',
endpoint: '/v1/chat/completions',
},
Ollama: {
name: 'Ollama',
url: 'http://localhost:11434',
model: 'llama3',
endpoint: '/api/chat',
},
Custom: {
name: 'Custom',
url: '',
model: '',
endpoint: '/v1/chat/completions',
},
};

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Provider default metadata (name/url/model/endpoint) is now duplicated in both Options.tsx (PROVIDER_DEFAULTS) and llmService.ts (getProviderDefaults). This duplication is likely to drift (e.g., changing a default endpoint in one place but not the other). Consider extracting shared defaults into a single module (e.g., under background/ or storage.types) and reusing it in both UI and service code.

Copilot uses AI. Check for mistakes.
Comment thread src/pages/popup/Popup.tsx
Comment on lines +27 to +34
// Get sorted providers from apiKeys with id, fallback to PROVIDERS
const sortedProviderItems = apiKeys.length > 0
? [...apiKeys].sort((a, b) => a.displayOrder - b.displayOrder)
: [];
// For display, use name; for selection, use id
const providerOptions = sortedProviderItems.length > 0
? sortedProviderItems.map((k) => ({ id: k.id, name: k.name }))
: PROVIDERS.map((p) => ({ id: p, name: p }));

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorting and display assume every stored APIKeyItem has displayOrder and name. Existing users may have older apiKeys entries (previous schema only had id/provider/key), which makes a.displayOrder - b.displayOrder yield NaN and renders undefined option labels. Consider normalizing apiKeys from storage (default displayOrder to index and name to provider) before sorting/mapping.

Copilot uses AI. Check for mistakes.
- Fix race condition in LLMService.request() by checking if controller is still current
- Fix handleTestApiKey to use user-configured model/endpoint instead of defaults
- Use replaceAll instead of replace for {{text}} placeholder
- Extract PROVIDER_DEFAULTS to shared storage.types.ts module
- Add auto-resize for prompt textareas on mount
- Add aria-hidden to info icon

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated 6 comments.

Comments suppressed due to low confidence (2)

src/pages/popup/Popup.tsx:44

  • selectedProvider is now treated as a provider id (options use apiKeys[].id), but on load you set provider directly from storage. If storage still contains the legacy provider name (e.g. "DeepSeek"), the controlled <select value={provider}> won't match any <option value={id}>, leaving the UI in an invalid/unselected state and persisting the legacy value. Normalize/migrate on load: when apiKeys exist, map legacy names to a matching apiKeys[].id (and consider writing back the id), and provide fallbacks when name/displayOrder are missing in older stored apiKeys.
  const [provider, setProvider] = useState<string>('DeepSeek');
  const [apiKeys, setApiKeys] = useState<APIKeyItem[]>([]);
  const [prompts, setPrompts] = useState<PromptTemplate[]>(DEFAULT_PROMPTS);
  const [selectedPromptId, setSelectedPromptId] = useState<string>('default-summary');
  const [notes, setNotes] = useState<NoteData[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentUrl, setCurrentUrl] = useState<string>('');
  const [siteDisabled, setSiteDisabled] = useState(false);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars -- used via functional setState update
  const [disabledSites, setDisabledSites] = useState<string[]>([]);

  // Get sorted providers from apiKeys with id, fallback to PROVIDERS
  const sortedProviderItems = apiKeys.length > 0
    ? [...apiKeys].sort((a, b) => a.displayOrder - b.displayOrder)
    : [];
  // For display, use name; for selection, use id
  const providerOptions = sortedProviderItems.length > 0
    ? sortedProviderItems.map((k) => ({ id: k.id, name: k.name }))
    : PROVIDERS.map((p) => ({ id: p, name: p }));

  useEffect(() => {
    // Load settings from storage
    chrome.storage.local.get(STORAGE_KEYS, (result: Partial<StorageSchema>) => {
      if (result.selectedProvider) setProvider(result.selectedProvider);
      if (result.apiKeys?.length) setApiKeys(result.apiKeys);
      if (result.prompts?.length) setPrompts(result.prompts);
      if (result.selectedPromptId) setSelectedPromptId(result.selectedPromptId);
      if (result.disabledSites) setDisabledSites(result.disabledSites);
    });

src/pages/options/Options.tsx:277

  • handleDeletePrompt updates storage but doesn’t clear promptUnsavedChanges[id], so the state map can accumulate stale entries over time (especially if users add/delete many templates). Consider deleting the key from promptUnsavedChanges (similar to how you clean up unsavedChanges on provider delete).
  const handleDeletePrompt = (id: string) => {
    const updated = prompts.filter((p) => p.id !== id);
    setPrompts(updated);
    saveToStorage({ prompts: updated });
  };

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 3 to 12
export interface APIKeyItem {
id: string;
provider: string;
name: string;
url: string;
key: string;
displayOrder: number;
model?: string; // Optional: provider-specific model (e.g., deepseek-chat, gpt-4)
endpoint?: string; // Optional: custom endpoint path (e.g., /v1/chat/completions)
}

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APIKeyItem now requires name, url, and displayOrder, but existing persisted data (from the prior schema) will not have these fields. Several call sites assume they exist (e.g. k.name.toLowerCase(), sorting by displayOrder, apiKeyItem.url), which can cause runtime crashes and/or force users to reconfigure. To keep upgrades safe, either make these fields optional with runtime normalization, or introduce a migration/normalization helper that backfills defaults (from PROVIDER_DEFAULTS + index-based order) when reading from storage.

Copilot uses AI. Check for mistakes.
Comment on lines +94 to +120
it('renders provider selector with sorted providers (by displayOrder)', async () => {
// Setup mock with apiKeys
vi.mocked(chrome.storage.local.get).mockImplementation((keys, callback) => {
callback(mockStorageWithApiKeys);
});
vi.mocked(chrome.storage.local.set).mockImplementation((data, callback) => {
if (callback) callback();
});

render(<Popup />);

await waitFor(() => {
const providerSelect = screen.getByLabelText(/provider/i) as HTMLSelectElement;
expect(providerSelect).toBeInTheDocument();

// OpenAI should be first (displayOrder: 0)
// Ollama should be second (displayOrder: 1)
// DeepSeek should be third (displayOrder: 2)
// Now uses 'id' as value, 'name' as display
const options = providerSelect.querySelectorAll('option');
expect(options[0].textContent).toBe('OpenAI API');
expect(options[0].value).toBe('2'); // id='2' (OpenAI)
expect(options[1].textContent).toBe('Local Ollama');
expect(options[1].value).toBe('3'); // id='3' (Ollama)
expect(options[2].textContent).toBe('DeepSeek API');
expect(options[2].value).toBe('1'); // id='1' (DeepSeek)
});

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Provider options now use id as the <option> value, but the test data still sets selectedProvider: 'DeepSeek' (legacy format) and the suite doesn't assert that the rendered <select> value matches a valid option. Add a test that covers the legacy->id migration/normalization behavior (e.g., stored name selects the matching id), so the UI doesn't regress into an unselected/invalid controlled state.

Copilot uses AI. Check for mistakes.
Comment on lines 136 to +145
const handleDeleteApiKey = (id: string) => {
const updated = apiKeys.filter((k) => k.id !== id);
setApiKeys(updated);
saveToStorage({ apiKeys: updated });
setUnsavedChanges((prev) => {
const next = { ...prev };
delete next[id];
return next;
});
};

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When deleting a provider, selectedProvider in storage may still point to the deleted provider id/name. That can leave the popup’s controlled provider <select> in an invalid/unselected state until the user manually changes it. Consider updating selectedProvider alongside apiKeys when the deleted id matches the current selection (e.g., set to the first remaining provider’s id, or clear it).

Copilot uses AI. Check for mistakes.
Comment on lines +82 to +90
// Sort providers by displayOrder
const sortedApiKeys = [...apiKeys].sort((a, b) => a.displayOrder - b.displayOrder);

// Get list of already added provider names
const addedProviderNames = apiKeys.map((k) => k.name.toLowerCase());
// Built-in providers that haven't been added yet
const availableBuiltIn = ['OpenAI', 'DeepSeek', 'SiliconFlow', 'TogetherAI', 'Ollama'].filter(
(p) => !addedProviderNames.includes(p.toLowerCase())
);

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

addedProviderNames is derived from apiKeys[].name, which is user-editable and may be missing in older stored data. This can both (1) crash at runtime (k.name undefined) and (2) allow duplicate built-in providers when users rename the display name (since you’re filtering by name, not provider type). Consider normalizing loaded apiKeys in the storage useEffect (fill name/url/displayOrder defaults) and computing availableBuiltIn from stable fields (k.provider) and/or PROVIDERS/isBuiltInProvider to avoid drift.

Copilot uses AI. Check for mistakes.
Comment on lines +204 to +209
const handleUpdateDisplayOrder = (id: string, value: string) => {
const order = parseInt(value) || 0;
const updated = apiKeys.map((k) => (k.id === id ? { ...k, displayOrder: order } : k));
setApiKeys(updated);
setUnsavedChanges((prev) => ({ ...prev, [id]: true }));
};

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

parseInt(value) || 0 will coerce an empty string (or any non-numeric input) to 0, which can unexpectedly jump a provider to highest priority just by clearing the input. Prefer an explicit Number.isNaN check and only update when the value is a valid integer (or keep it as a string until save) to avoid accidental reordering.

Copilot uses AI. Check for mistakes.
Comment on lines +353 to +367
<button
className="reset-btn"
onClick={() => handleResetToDefaults(item.id, item.provider)}
title="Reset to defaults"
disabled={item.provider === 'Custom'}
>
<RefreshIcon />
</button>
<button
className="delete-btn"
onClick={() => handleDeleteApiKey(item.id)}
title="Delete provider"
>
<TrashIcon />
</button>

Copilot AI Mar 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These icon-only action buttons rely on title for labeling, which doesn't reliably provide an accessible name for screen readers. Add aria-label (or visible text) for Reset/Delete (and any other icon-only buttons) so they are keyboard/screen-reader accessible.

Copilot uses AI. Check for mistakes.
@luorome31
luorome31 merged commit 55948bc into main Mar 29, 2026
4 checks passed
@luorome31
luorome31 deleted the feat/T011-T012-popup-options-ui branch March 29, 2026 09:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants